package itpenguin.review;

import itpenguin.common.PMFactory;
import itpenguin.review.entities.Item;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class DownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		PersistenceManager pm = null;
		Collection<Item> items = null;
		try {
			pm = PMFactory.getInstance().getPersistenceManager();
			Query query = pm.newQuery("select from itpenguin.review.entities.Item");  
			items = (Collection<Item>) query.execute();
			items = pm.detachCopyAll(items);

		} finally {
			pm.close();
		}
		
		List<List<Object>> list = new ArrayList<List<Object>>();
		for(Item item : items) {
			List<Object> review = new ArrayList<Object>();
			review.add(item.getItemId());
			review.add(item.getAsin());
			review.add(item.getReviewTitle());
			review.add(item.getReviewDate());
			review.add(item.getReview());
			review.add(item.getScore());
			review.add(item.getRelatedAsins());
			list.add(review);
		}
		
		Gson gson = new Gson();
		String json = gson.toJson(list);
		
		resp.setContentType("application/json");
		resp.setCharacterEncoding("UTF-8");
		resp.getWriter().println(json);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		PersistenceManager pm = PMFactory.getInstance().getPersistenceManager();
        ServletFileUpload upload = new ServletFileUpload();
		FileItemIterator iterator;
		InputStreamReader reader = null;
		try {
			iterator = upload.getItemIterator(req);
			while (iterator.hasNext()) {
				FileItemStream item = iterator.next();
				if (!item.isFormField()) { 
					reader = new InputStreamReader(item.openStream(), "UTF-8");
				}
				break;
			}
		} catch (FileUploadException e) {
			throw new ServletException(e);
		}
		
		Gson gson = new Gson();
		JsonParser parser = new JsonParser();
		JsonArray array = parser.parse(reader).getAsJsonArray();
		Date now = new Date();
		for (JsonElement element : array) {
			JsonArray review = element.getAsJsonArray();
			Item item = new Item(gson.fromJson(review.get(0), String.class));
			item.setAsin(gson.fromJson(review.get(1), String.class));
			item.setReviewTitle(gson.fromJson(review.get(2), String.class));
			item.setReviewDate(gson.fromJson(review.get(3), Date.class));
			item.setReview(gson.fromJson(review.get(4), String.class));
			item.setScore(gson.fromJson(review.get(5), Short.class));
			JsonArray relatedAsins = review.get(6).getAsJsonArray();
			item.getRelatedAsins().clear();
			for (JsonElement asin : relatedAsins) {
				item.getRelatedAsins().add(asin.getAsString());
			}
			item.setLastModified(now);
//			try {
//				item.updateItemInfo();
//			} catch (XMLStreamException e) {
//				throw new ServletException(e);
//			}
			pm.makePersistent(item);
		}
		pm.close();
	}

}
